
// rem适配
(function (doc, win) {
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        onResize = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            if (clientWidth <= 320) {
                docEl.style.fontSize = '31.25px';
            } else if (clientWidth > 320 && clientWidth <= 1024) {
                docEl.style.fontSize = 100 * (clientWidth / 1024) + 'px';
                docEl.style.overflowX = 'hidden';
            } else {
                docEl.style.fontSize = 100 + 'px';
                docEl.style.overflowX = 'hidden';
            }
        };
    var ready = false;
    if (ready == false) {
        ready = true;
        var clientWidth = docEl.clientWidth;
        if (!clientWidth) return;
        if (clientWidth <= 320) {
            docEl.style.fontSize = '31.25px';
        } else if (clientWidth > 320 && clientWidth <= 1024) {
            docEl.style.fontSize = 100 * (clientWidth / 1024) + 'px';
        } else {
            docEl.style.fontSize = 100 + 'px';
        }
    }
    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, onResize, false);
    doc.addEventListener('DOMContentLoaded', onResize, false);
})(document, window);

$(function () {

    // 初始化数据
    var timer;
    var score = 0;
    var counter = 0;
    var clickedCellArr = [];
    var intervalTime = 5;
    var monsterMsg = {};
    var contrastData = 0;
    var canvasIndex = 0;
    var cellsMsgObj = {};
    var cellsMsgArr = [];
    var cellsAbleArr = [];
    var gridCells = $(".grid-container>.grids>.grid-cell");
    var cellsArray = setTableAttr(5, 6);
    //各页面之间的切换
    //游戏说明页面
    $(".desc").on("click", function () {
        $(".pages>.game-description").addClass("current").siblings().removeClass("current");
    });
    $(".prevPageBtn").on("click", function () {
        $(".game-description>.descPage_1").fadeIn().siblings().hide();
    });
    $(".nextPageBtn").on("click", function () {
        $(".game-description>.descPage_2").fadeIn().siblings().hide();
    });
    //点击开始按钮进入游戏页面
    $(".playBtn").on("click", function () {
        $(".pages>.game-container").addClass("current").siblings().removeClass("current");
        newGame(cellsArray);
    });


    //点击再来一次按钮进入游戏页面
    $(".playAngie").on("click", function () {
        $(".pages>.game-container").addClass("current").siblings().removeClass("current");
        newGame(cellsArray);
    });


    //======= 游戏页逻辑 开始   =======

    function newGame(cellsArray) {
        $(".game-container .score").html(score);
        $(".endPage .score").html(score);

        monsterMsg = setMonster();
        contrastData = monsterMsg.contrastData;
        canvasIndex = monsterMsg.canvasIndex + 6;
        cellsMsgObj = setCellsAbleArr(cellsArray,score, 6, 0);
        cellsMsgArr = cellsMsgObj.cellsMsgArr;
        cellsAbleArr = cellsMsgObj.cellsAbleArr;
        // console.log(cellsMsgObj, contrastData);
        // console.log(cellsMsgArr);

        //给每一个格子注册点击事件
        gridCells.on("click", function () {
            if ($(this).html()) {
                var audio1 = document.getElementById('music1');
                audio1.play();
                var sum = 0;
                var dataNum = $(this).attr("data-num");
                // console.log(dataNum);

                // 将点击过的格子 信息存储到clickedCellArr数组中
                for (var i = 0; i < cellsMsgArr.length; i++) {
                    if (cellsMsgArr[i].cellIndex == dataNum) {
                        clickedCellArr.push({dataNum: dataNum, result: cellsMsgArr[i].dataResult});
                    }
                }
                if ($(this).hasClass("clicked")) { //如果格子被点击过再次点击时取消选中的格子
                    // 将选中的格子的信息项从clickedCellArr数组中去除
                    clickedCellArr = clickedCellArr.filter(function (item) {
                        return item.dataNum !== dataNum;
                    });
                    $(this).removeClass("clicked");
                } else { //选中曾凑数成功被消除过的格子
                    $(this).addClass("clicked");
                    // 去除clickedCellArr数组中的重复项
                    if (clickedCellArr.length > 0) {
                        clickedCellArr = clickedCellArr.unique();
                    }
                }
                // console.log(clickedCellArr);

                // console.log("cellsMsgArr:" + cellsMsgArr, "clickedCellArr:" + clickedCellArr);

                if (contrastData == 0 && clickedCellArr.length == 0) {
                    sum = 10;
                } else {
                    //计算被点击过的格子中数字之和
                    clickedCellArr.forEach(function (item) {
                        sum += item.result * 600;
                    });
                }
                // console.log(sum, contrastData*600);

                // 凑数成功
                if (sum === contrastData*600) {
                    // 记录被点击过的格子的坐标
                    if (clickedCellArr.length > 1) {
                        // console.log(clickedCellArr);
                        var coordinateArr = (function (clickedCellArr) {
                            var arr = [];
                            clickedCellArr.forEach(function (item) {
                                var cellIndex = item.dataNum;
                                var row = cellIndex.slice(0, 1);
                                var column = cellIndex.slice(1);
                                var gridCell = $("#grid-cell-" + row + "-" + column);
                                var x = parseFloat(gridCell.css("left")) + 49;
                                var y = parseFloat(gridCell.css("top")) + 49;
                                // console.log("x:" + x, "y:" + y);
                                arr.push({dataNum:cellIndex,x: x, y: y});
                            });
                            return arr;
                        })(clickedCellArr);
                        // console.log(coordinateArr);
                        // 被点击过的格子超过两个时，按照点击顺序记录奇数项格子的中心坐标，
                        // 和相邻两个格子的距离以及与x轴的夹角
                        var angleArr = [];
                        if (coordinateArr.length > 1) {
                            var angle, h, w, positionX, positionY, scaleX;
                            for (var k = 0; k < coordinateArr.length - 1; k++) {
                                h = coordinateArr[k + 1].y - coordinateArr[k].y;
                                w = coordinateArr[k + 1].x - coordinateArr[k].x;
                                if (h == 0 && w > 0) {
                                    angle = 0;
                                } else if (h == 0 && w < 0) {
                                    angle = -180;
                                } else if (w == 0 && h > 0) {
                                    angle = 90;
                                } else if (w == 0 && h < 0) {
                                    angle = -90;
                                } else if (h > 0 && w > 0) {
                                    angle = 180 * Math.atan(h/w) / Math.PI;
                                } else if (h < 0 && w > 0) {
                                    angle = 360 + 180 * Math.atan(h/w) / Math.PI;
                                } else if (h > 0 && w < 0) {
                                    angle = 180 + 180 * Math.atan(h/w) / Math.PI;
                                } else if (h < 0 && w < 0) {
                                    angle = 180 + 180 * Math.atan(h/w) / Math.PI;
                                }

                                positionX = coordinateArr[k].x;
                                positionY = coordinateArr[k].y;
                                scaleX = Math.sqrt(h * h + (w * w)) / 276;

                                angleArr.push({
                                    top: positionY,
                                    left: positionX,
                                    scaleX: scaleX,
                                    angle: angle
                                });
                            }
                        }
                        // console.log(angleArr);
                        initLineAnima(angleArr,timer, loadElectricAnima);
                    } else {
                        loadElectricAnima()
                    }
                }
            }
        });

        //在随机2个格子生成数字
        timer = setInterval(intervalFun, intervalTime * 1000);
    }

    //凑数成功电流动画显示并播放
    function loadElectricAnima() {
        $("#canvas14").show();
        var animaIndex = animaCreateJs.prototype.getIndexById("canvas14");
        var animaObj = animaCreateJs.prototype.animationArr[animaIndex];
        var anima = animaObj["anima"];
        anima.gotoAndPlay(0);

        clearInterval(timer);
        // console.log(timer);
        var totalFrames = anima.totalFrames;
        var currentFrame = 0;
        // console.log(totalFrames);

        //凑数成功电流动画播放到24帧时小怪兽出场动画停在第一帧，小怪兽对应的电击效果动画显示并播放
        var theMonsterIndex = animaCreateJs.prototype.getIndexById("canvas" + (canvasIndex-6 + 1));
        var theMonsterObj = animaCreateJs.prototype.animationArr[theMonsterIndex];
        var theMonster = theMonsterObj["anima"];

        var theAnima = $(".monster>#canvas" + (canvasIndex + 1));
        var monsterIndex = animaCreateJs.prototype.getIndexById("canvas" + (canvasIndex + 1));
        var monsterObj = animaCreateJs.prototype.animationArr[monsterIndex];
        var monster = monsterObj["anima"];
        var totalFrame = monster.totalFrames;
        // console.log(totalFrames);
        var crtFrame = 0;
        anima.addEventListener("tick", animaControllerPlaying);
        function animaControllerPlaying() {
            currentFrame++;
            if(currentFrame == 8){
                var audio2 = document.getElementById('music2');
                audio2.volume = 0.4;
                audio2.play();
            } else if (currentFrame == 24) {
                //当电流击中小怪兽时，将点击过的单元格清空并重置点击过的单元格的数字之和，
                clickedCellArr.forEach(function (item) {
                    var cellIndex = item.dataNum;
                    var row = cellIndex.slice(0, 1);
                    var column = cellIndex.slice(1);
                    var gridCell = $("#grid-cell-" + row + "-" + column);

                    gridCell.html("").removeClass("clicked");

                    // console.log("清空凑数成功的格子");
                    //并将cellsMsgArr中存储对应的格子信息的项删除
                    cellsMsgArr.forEach(function (item, index) {
                        if (item.cellIndex == cellIndex) {
                            cellsMsgArr.splice(index, 1);
                            // console.log("将凑数成功的格子从数组中清除");
                        }
                    });
                });

                sum = 0;

                // 小怪兽出场动画停在第一帧，要匹对的数据格子置为空，电击小怪兽动画显示并播放
                theMonster.gotoAndStop(0);
                $(".contrastData").html("");
                theAnima.show().siblings("canvas").hide();
                $("#canvas18").show();
                var defenAnimaIndex = animaCreateJs.prototype.getIndexById("canvas18");
                var defenAnimaObj = animaCreateJs.prototype.animationArr[defenAnimaIndex];
                var defenAnima = defenAnimaObj["anima"];
                var tFrames = defenAnima.totalFrames;
                defenAnima.gotoAndPlay(0);
                var cFrame = 0;
                defenAnima.addEventListener("tick", defenAnimaControllerPlaying);
                function defenAnimaControllerPlaying(){
                    cFrame++;
                    if(cFrame == tFrames){  //得分动画结束后隐藏动画并重新随机显示小怪兽和要匹配的随机数字
                        defenAnima.removeEventListener("tick", defenAnimaControllerPlaying);
                        // 计算得分，并在得分区显示分数
                        score += 10 * Math.pow(clickedCellArr.length, 2) + 50 * clickedCellArr.length;
                        $(".game-container .score").html(score);
                        $(".endPage .score").html(score);
                        $("#canvas18").hide();
                    }
                }
                // console.log(canvasIndex + 1);
                // console.log("播放电击");
                monster.gotoAndPlay(0);
                monster.addEventListener("tick", monsterControllerPlaying);
            } else if (currentFrame == totalFrames + 24) {
                anima.gotoAndStop(0);
                anima.removeEventListener("tick", animaControllerPlaying);
                $("#canvas14").hide();


            }
        }

        function monsterControllerPlaying() {
            crtFrame++;
            // console.log(crtFrame, totalFrame);
            if (crtFrame === totalFrame) {
                //清空存储 点击过的单元格 的信息的数组
                clickedCellArr = [];
                theAnima.hide();
                //电击小怪兽动画结束后隐藏动画并开始得分动画
                monster.removeEventListener("tick", monsterControllerPlaying);
                monsterMsg = setMonster();
                canvasIndex = monsterMsg.canvasIndex + 6;
                contrastData = monsterMsg.contrastData;
                timer = setInterval(intervalFun, intervalTime * 1000);
                // console.log(timer);
                // console.log(canvasIndex,contrastData);
            }
        }
    }

    //定时函数，随机生成数字，并在格子填满时结束游戏，重置数据
    function intervalFun() {
        //统计单元格中正负数的个数之差
        var flag1 = 0, flag2 = 0;
        for (var i = 0; i < cellsMsgArr.length; i++){
            // console.log(typeof cellsMsgArr[i].arrItem, typeof cellsMsgArr[i].arrItem == "number");
            if (typeof cellsMsgArr[i].arrItem == "number"  &&  cellsMsgArr[i].arrItem> 0) {
                flag1 += 1;
            } else if (typeof cellsMsgArr[i].arrItem == "number"  && cellsMsgArr[i].arrItem < 0) {
                // console.log( cellsMsgArr[i].arrItem);
                flag2 += 1;
            }
        }
        var flag = flag1 - flag2;

        // console.log(flag,flag1,flag2);
        cellsMsgObj = setCellsAbleArr(cellsArray,score,3, flag);
        cellsAbleArr = cellsMsgObj.cellsAbleArr;
        // console.log(cellsAbleArr);

        //有空的单元格时
        if (cellsAbleArr.length >= 0) {
            // console.log(cellsMsgArr);
            // console.log(cellsMsgObj, cellsMsgArr);
            if (cellsMsgArr.length >= 27) {
                // console.log("30个格子全部填满，游戏结束");
                //单元格全部填满数字后，清除定时器，不再随机产生数字
                clearInterval(timer);
                // return;
                //当单元格被数字填满后，游戏结束动画播放
                $("#canvas15").show();
                var gameOverAnimaIndex = animaCreateJs.prototype.getIndexById("canvas15");
                var gameOverAnimaObj = animaCreateJs.prototype.animationArr[gameOverAnimaIndex];
                var gameOverAnima = gameOverAnimaObj["anima"];
                gameOverAnima.gotoAndPlay(0);

                // console.log("gameOver:" + gameOverAnima);
                var totalFrames = gameOverAnima.totalFrames;
                var currentFrame = 0;
                gameOverAnima.addEventListener("tick", gameOverAnimaController);
                function gameOverAnimaController() {
                    currentFrame++;
                    if (currentFrame == totalFrames) {
                        //当游戏结束动画播放完毕后，结束页面显示并隐藏动画
                        gameOverAnima.removeEventListener("tick", gameOverAnimaController);
                        $("#canvas15").hide();
                        $(".pages>.endPage").addClass("current").siblings().removeClass("current");

                        //游戏结束重置数据并取消单元格的点击事件
                        $(".contrastData").html("");
                        gridCells.off("click");
                        gridCells.removeClass("clicked");
                        score = 0;
                        counter = 0;
                        monsterMsg = {};
                        canvasIndex = 0;
                        cellsMsgObj = {};
                        cellsMsgArr = [];
                        cellsAbleArr = [];
                        clickedCellArr = [];
                    }
                }
            } else if (cellsMsgArr.length < 27) {
                //当单元格被数字填满前，合并存储已被数字填充过的单元格信息的数组
                cellsMsgArr = cellsMsgArr.concat(cellsMsgObj.cellsMsgArr);
            }
        }
        // console.log(cellsMsgArr,cellsAbleArr);

    }

//=======  游戏页逻辑 结束   =======

});


